//app.js
var util = require('./utils/util.js');
var getInfo = util.getInfo;
App({
  onLaunch: function (options) {
    //检查登录
    let that = this;
    /*if (options.path != 'pages/jump/jump' && options.path != 'pages/reward/reward' && options.path != 'pages/more/more'){
      that.checkLogin();
    }*/
    if (options.path == 'pages/index/index' || options.path == 'pages/details/details') {
      that.checkLogin();
    }

    var t = options.query.t;
    //console.log(options.path);
    this.globalData.t = t;

    // 展示本地存储能力
    //var logs = wx.getStorageSync('logs') || []
    //logs.unshift(Date.now())
    //wx.setStorageSync('logs', logs);

    // let params = {
    //   m: 'check_we_app'
    // };
    // getInfo(params).then(res => {
    //   console.log(res);
    //   if (res.result == 0) {
    //     wx.redirectTo({
    //       url: '../../pages/kefu/kefu',
    //     })
    //   }
    // })



    // 登录
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //     console.log(res)
    //   }
    // })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          // wx.getUserInfo({
          //   success: res => {
          //     // console.log(res);
          //     // 可以将 res 发送给后台解码出 unionId
          //     this.globalData.userInfo = res.userInfo;
          //     // console.log(this.globalData.userInfo);

          //     // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          //     // 所以此处加入 callback 以防止这种情况
          //     if (this.userInfoReadyCallback) {
          //       this.userInfoReadyCallback(res)
          //     }
          //   }
          // })
        }
      }
    })
    that.getLbs()
  },
  globalData: {
    isLogin: false,   //是否登录
    user: null,       //微信获取的用户信息
    userInfo: null,  //后台请求回来的用户数据
    commonUrl: 'https://wxb.whwangdoudou.cn/pdd.php',   //api地址
    t: '',
    latitude: '',
    longitude: ''
  },
  checkLogin() {
    let that = this;
    //检查localstorage里有没有kuaiyong
    let kuaiyong = wx.getStorageSync('kuaiyong');
    if (!kuaiyong) {
      that.wxLogin();
    }
    else {
      let p = {
        m: 'xlogin',
        kuaiyong: kuaiyong,
        i: '6'
      };
      getInfo(p).then(res => {
        //console.log(res);
        if (res.errcode == -1000 && res.r == -1) {
          that.wxLogin();
        }
        else {
          if (res.check_phone == 0) {
            wx.setStorageSync('uid', res.uid);
            wx.setStorageSync('userinfo', res.info);

            var weapp_openid = res.info.openId;
            wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId
            // wx.switchTab({
            //   url: '../index/index',
            // });
          }
          else if (res.check_phone == 1) {
            if (res.phone_ok == 1) {
              wx.setStorageSync('uid', res.uid);
              wx.setStorageSync('userinfo', res.info);

              var weapp_openid = res.info.openId;
              wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId
              // wx.switchTab({
              //   url: '../index/index',
              // });
            }
            else if (res.phone_ok == 0) {
              wx.setStorageSync('uid', res.uid);

              var weapp_openid = res.info.openId;
              wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId

              wx.navigateTo({
                url: '../../pages/phone/phone',
              })
            }
          }
        }
      })
    }
  },
  wxLogin() {
    var that = this;
    var code, encryptedData, iv;
    // 调用微信登录接口获取code
    wx.login({
      success: res => {
        //console.log(res);
        code = res.code;
        // 调用getUserInfo获取encryptedData和iv
        wx.getUserInfo({//getUserInfo流程
          success: function (res2) {//获取userinfo成功
            //console.log(res2);
            encryptedData = res2.encryptedData;
            iv = res2.iv;
            // 和后台交互获取session
            that.Login(code, encryptedData, iv);
          },
          fail(e) {
            //console.log(e)
          }
        })
      }
    });

  },
  Login(code, encryptedData, iv) {
    var that = this;
    var defaultUrl = that.globalData.commonUrl;
    var t = that.globalData.t;
    wx.showToast({
      title: '正在登录...',
      icon: 'loading',
      duration: 10000
    });
    //请求服务器
    let p = {};
    if (!t) {
      p = {
        m: 'xlogin',
        code: code,
        encryptedData: encryptedData,
        iv: iv,
        i: '6'
      }
    }
    else {
      p = {
        m: 'xlogin',
        code: code,
        encryptedData: encryptedData,
        iv: iv,
        t: t,
        i: '6'
      }
    }
    wx.request({
      url: defaultUrl,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      dataType: 'josn',
      data: p,
      success: function (res) {
        wx.hideToast();
        var data = res.data.trim();   //去除空格
        data = JSON.parse(data);      //字符串转json
        //console.log(data);
        if (data.check_phone == 0) {
          // 将用户信息存至localstorage
          // wx.setStorageSync('userinfo', res);
          // 将kuaiyong和uid存入storage中
          var weapp_openid = data.info.openId;
          wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId

          wx.setStorageSync('kuaiyong', data.kuaiyong);
          wx.setStorageSync('uid', data.uid);
          // wx.switchTab({
          //   url: '../index/index',
          // });
        }
        else if (data.check_phone == 1) {
          var weapp_openid = data.info.openId;
          wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId

          wx.setStorageSync('kuaiyong', data.kuaiyong);
          wx.setStorageSync('uid', data.uid);

          if (data.phone_ok === 0) {
            // 未绑定手机号，跳转至验证手机页面
            wx.showModal({
              title: '温馨提示',
              content: '当前账户尚未绑定手机，是否前往绑定',
              success: function (res) {
                if (res.confirm) {
                  //console.log('用户点击确定');
                  wx.navigateTo({
                    url: './pages/phone/phone',       //前往绑定手机页
                  })
                } else if (res.cancel) {
                  //console.log('用户点击取消')
                }
              }
            })
          }
          else if (data.phone_ok === 1) {
            // wx.showToast({
            //   title: '登录成功，前往首页!',
            // });
            // 将用户信息存至localstorage
            // wx.setStorageSync('userinfo', res);
            // 将kuaiyong和uid存入storage中
            // wx.switchTab({
            //   url: './pages/index/index',
            // });
          }
        }
      },
      fail: function () {
        //console.log('登录失败');
      }
    })
  },

  getLbs() {
    let that = this;
    that.village_LBS(that)
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '位置信息授权',
            content: '位置授权暂未开启动',
            confirmText: '开启授权',
            cancelText: '仍然拒绝',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用getLocationt的API
                      getLocation(that);
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success_no_circle',
                        duration: 1000
                      })
                    }
                  }
                })
                that.village_LBS(that)
              } else if (res.cancel) {
                // console.log('用户点击取消')
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
          that.village_LBS(that)
        }
        else {
          // console.log("用户已开启定位授权");
        }
      }
    })
  },
  village_LBS() {
    let that = this;
    wx.getLocation({
      success(res) {
        that.globalData.latitude = res.latitude
        that.globalData.longitude = res.longitude
      },
      fail(res) {
        //console.log(res)
      }
    })
  },
})